/*
   Contest - model class
*/
package com.semanticbits.codejam.model

import app.*
import ariba.appcore.*
import ariba.ui.meta.annotations.*
import ariba.ui.meta.annotations.Property.*
import ariba.ui.meta.persistence.*
import ariba.appcore.annotations.*
import org.compass.annotations.*
import javax.mail.internet.*;
import javax.mail.*
import javax.activation.*
import javax.persistence.*
import java.util.*
import org.apache.commons.httpclient.*
import org.apache.commons.httpclient.auth.*
import org.apache.commons.httpclient.methods.*
import ariba.ui.meta.annotations.Property.Visible
import ariba.ui.meta.annotations.Trait.Required

@Entity @NavModuleClass @Searchable
@DefaultAccess @AnonymousAccess([Permission.ClassOperation.view])
class Contest
{
   @Id @GeneratedValue @SearchableId
   private Long id

   boolean published = false
   boolean completed = false

   @Required @SearchableProperty @Trait.LabelField
   String title

   @Trait.RichText
   String problemStatement

   @Required
   java.util.Date startDate
   @Required
   java.util.Date  dueDate

   int numberOfAllowableEntries = 1

   @ManyToOne User owner = User.currentUser();

   //@OneToMany @SearchableComponent
   //List <Submission> details = new ArrayList<Submission>()

   @Required @ManyToOne
   EmailTemplate emailTemplate

   @OneToMany
   List <Awards> awards = new ArrayList<Awards>()

   protected String jobName = UUID.randomUUID();


   public void send(){


   def  d_email = Application.MAIL_FROM,
        d_uname = Application.MAIL_USER,
        d_password = Application.MAIL_PASSWORD,
        d_host = Application.MAIL_HOST,
        d_port  = Application.MAIL_PORT, //465,587
        m_to = Application.MAIL_TOLIST;


   def m_subject = "ANNOUNCE: Code Jam - ${title}"

   def m_text = emailTemplate.applyTemplate( emailTemplate.announcementTemplate, this);

    def props = new java.util.Properties()
    props.put("mail.smtp.user", d_email)
    props.put("mail.smtp.host", d_host)
    props.put("mail.smtp.port", d_port)
    props.put("mail.smtp.starttls.enable","true")
    props.put("mail.smtp.debug", "true");
    props.put("mail.smtp.auth", "true")
    props.put("mail.smtp.socketFactory.port", d_port)
    props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory")
    props.put("mail.smtp.socketFactory.fallback", "false")

    def auth = new SMTPAuthenticator()
    def session = Session.getInstance(props, auth)
    session.setDebug(true);

    def msg = new MimeMessage(session)
    msg.setText(m_text)
    msg.setSubject(m_subject)
    msg.setFrom(new InternetAddress(d_email))
    msg.addRecipient(Message.RecipientType.TO, new InternetAddress(m_to))

    Transport transport = session.getTransport("smtps");
    transport.connect(d_host, d_port, d_uname, d_password);
    transport.sendMessage(msg, msg.getAllRecipients());
    transport.close();
  }

   @Action(message="Contest Announced!") @Visible('${!properties.editing}')
  void announce()
  {
  if( published ) return;
  published = true;




  def subject = "ANNOUNCE: Code Jam - ${title}"
  def text = emailTemplate.applyTemplate( emailTemplate.announcementTemplate, this);

  emailTemplate.saveMessage(this, emailTemplate.applyTemplate( text, this), "ann" );


  HudsonClient client = new HudsonClient();

  //client.hudsonHost="localhost:8081";
  client.projectName = this.jobName
  //client.server = "localhost:8081"
  client.hudsonHost = "${Application.HUDSON_URL}/hudson"
  client.username = "username"
  client.password = "password"
  client.config_xml =
"""
<?xml version='1.0' encoding='UTF-8'?>
<project>
  <actions/>
  <description></description>
  <keepDependencies>false</keepDependencies>
  <properties/>
  <scm class="hudson.scm.NullSCM"/>
  <canRoam>true</canRoam>
  <disabled>false</disabled>
  <blockBuildWhenUpstreamBuilding>false</blockBuildWhenUpstreamBuilding>
  <triggers class="vector"/>
  <concurrentBuild>false</concurrentBuild>
  <builders>
    <hudson.tasks.Ant>
      <targets>-lib ${Application.SHARED_DIR}/lib</targets>
      <buildFile>${Application.SHARED_DIR}/${this.jobName}/build.xml</buildFile>
    </hudson.tasks.Ant>
  </builders>
  <publishers/>
  <buildWrappers/>
</project>"""

  client.createProject()

  println client.checkProject()

  // if not immediate
  client.build()

  //delete if needed
  //client.deleteProject()
  }

  @Action(message="Contest Scheduled!") @Visible('${!properties.editing}')
  void schedule()
  {
  if( published ) return;
  published = true;

  HudsonClient client = new HudsonClient();

//client.hudsonHost="localhost:8081";
    client.projectName = this.jobName
    //client.server = "localhost:8081"
    client.hudsonHost = "${Application.HUDSON_URL}/hudson"

  client.username = "username"
  client.password = "password"
  client.config_xml =
"""
<?xml version='1.0' encoding='UTF-8'?>
<project>
  <actions/>
  <description></description>
  <keepDependencies>false</keepDependencies>
  <properties/>
  <scm class="hudson.scm.NullSCM"/>
  <canRoam>true</canRoam>
  <disabled>false</disabled>
  <blockBuildWhenUpstreamBuilding>false</blockBuildWhenUpstreamBuilding>
  <triggers class="vector">
    <hudson.triggers.TimerTrigger>
      <spec>0 0 ${this.startDate.day} ${this.startDate.month + 1} *</spec>
    </hudson.triggers.TimerTrigger>
  </triggers>
  <concurrentBuild>false</concurrentBuild>
  <builders>
    <hudson.tasks.Ant>
      <targets>-lib "${Application.SHARED_DIR}/lib</targets>
      <buildFile>"${Application.HUDSON_URL}/build.xml</buildFile>
    </hudson.tasks.Ant>
  </builders>
  <publishers/>
  <buildWrappers/>
</project>"""

  client.createProject()

  client.checkProject()

  //client.deleteProject()
  }

  @Action(message="Winner Announced!") @Visible('${!properties.editing}')
  void end()
  {
    if( completed ) return;
    completed = true;

    def subject = "ANNOUNCE: Winner Code Jam - ${title}"
    def text = emailTemplate.applyTemplate( emailTemplate.winnerTemplate, this);

    emailTemplate.saveMessage(this, emailTemplate.applyTemplate( text, this), "ann" );


    HudsonClient client = new HudsonClient();

      client.projectName = this.jobName
      client.hudsonHost = "${Application.HUDSON_URL}/hudson"
      client.username = "username"
      client.password = "password"
      client.config_xml =
    """
    <?xml version='1.0' encoding='UTF-8'?>
    <project>
      <actions/>
      <description></description>
      <keepDependencies>false</keepDependencies>
      <properties/>
      <scm class="hudson.scm.NullSCM"/>
      <canRoam>true</canRoam>
      <disabled>false</disabled>
      <blockBuildWhenUpstreamBuilding>false</blockBuildWhenUpstreamBuilding>
      <triggers class="vector"/>
      <concurrentBuild>false</concurrentBuild>
      <builders>
        <hudson.tasks.Ant>
          <targets>-lib "${Application.SHARED_DIR}/lib</targets>
          <buildFile>"${Application.HUDSON_URL}/${client.projectName}/build.xml</buildFile>
        </hudson.tasks.Ant>
      </builders>
      <publishers/>
      <buildWrappers/>
    </project>"""

      client.createProject()

      println client.checkProject()

      // if not immediate
      client.build()

      //delete if needed
      //client.deleteProject()

    }

}


class SMTPAuthenticator extends Authenticator
{
    public PasswordAuthentication getPasswordAuthentication()
    {
        return new PasswordAuthentication('email@gmail.com', 'test1234');
    }
}